import type { IMobileLoginParams } from '@/api/types/login'
import apiTest from '@/api/user'
import { useUserStore } from '@/store/user'
import { toast } from '@/utils/toast'

export function useLogin(ress) {
  // 展示的数据  可以通过App.vue 界面去隐藏
  const user_store = useUserStore()
  function getPhoneNumber({ detail }) {
    return new Promise((resolve, reject) => {
      uni.getProvider({
        service: 'oauth',
        success(res) {
          console.log(res)
        },
        fail(err) {
          console.error('获取服务提供商失败', err)
          reject(err)
        },
      });

      uni.login({
        provider: 'weixin',
        success: ({ code }) => {
          console.log(code, 'getWxCode')
          apiTest.tokenSocial({ js_code: code, platform: 20 })
            .then((val) => {
              console.log('tokenSocial', val)
              if (val.result && typeof val.result === 'object' && 'wxId' in val.result) {
                if (detail.errMsg === 'getPhoneNumber:ok') {
                  const data = {
                    code: detail.code,
                    clientInfoType: '20',
                    wxId: val.result.wxId,
                    roleType: "20",
                    inviterId: uni.getStorageSync('inviteCode'),
                  }
                  const shareId = uni.getStorageSync('shareId');
                  if (shareId) {
                    data.inviterId = shareId
                  }
                  apiTest
                    .tokenSocial2(data)
                    .then((res) => {
                      console.log(res, 'res')
                      // 使用安全的状态检查
                      if (res && res.status === 1) {
                        user_store.getUserInfo().then(() => {
                          uni.navigateBack()
                          resolve('success')
                        }).catch((err) => {
                          console.error('获取用户信息失败', err)
                          toast.error('获取用户信息失败')
                          resolve('fail')
                        })
                      }
                      else {
                        console.log('登录失败，状态码不为1')
                        toast.error(res.message || '登录失败')
                        resolve('fail')
                      }
                    })
                    .catch((fail) => {
                      console.error('登录失败', fail)
                      toast.error('登录失败，请稍后重试')
                      resolve('fail')
                    })
                }
                else {
                  console.log('用户取消授权', detail.errMsg)
                  toast.info('您取消了授权')
                  resolve('fail')
                }
              }
              else {
                console.error('获取微信ID失败', val)
                toast.error(val.message || '登录失败')
                resolve('fail')
              }
            })
            .catch((err) => {
              console.error('获取微信ID接口调用失败', err)
              toast.error('登录失败，请稍后重试')
              resolve('fail')
            })
        },
        fail: (err) => {
          console.error('微信登录失败', err)
          toast.error('微信登录失败，请稍后重试')
          resolve('fail')
        },
        complete: () => {
          // 完成时不做任何处理，让外层处理loading状态
        },
      })
    })
  }

  function getSendCode(mobile, codeType = 10) {
    return new Promise((resolve, reject) => {
      console.log('调用sendcode API，参数:', { mobile, codeType })
      apiTest.sendcode({ mobile, codeType }).then((val) => {
        console.log('sendcode API返回结果:', val)
        const isSuccess = val && (val.success === true || val.status === 1)
        resolve(isSuccess)
      }).catch((err) => {
        console.error('发送验证码失败', err)
        reject(err)
      })
    })
  }

  // 手机号验证码登录
  function mobileLoginWithSms(params: IMobileLoginParams) {
    return new Promise<string>((resolve, reject) => {
      console.log('调用手机号登录API，参数:', params)
      apiTest.mobileLogin(params).then((res) => {
        console.log('手机号登录API返回结果:', res)
        const isSuccess = res && (res.success === true || res.status === 1)
        if (isSuccess) {
          // 登录成功，保存token并获取用户信息
          if (res.result && typeof res.result === 'object' && 'ticket' in res.result) {
            // 保存token到本地存储
            const token = res.result.ticket
            uni.setStorageSync('token', token)
            user_store.userInfo.token = token

            console.log(user_store, 'user_storeuser_storeuser_store');

            // 获取用户信息
            user_store.getUserInfo().then(() => {
              resolve('success')
            }).catch((err) => {
              console.error('获取用户信息失败', err)
              reject(err)
            })
          }
          else {
            resolve('fail')
          }
        }
        else {
          // 登录失败
          uni.showToast({
            title: res.message || '登录失败',
            icon: 'none',
          })
          resolve('fail')
        }
      }).catch((err) => {
        console.error('手机号登录失败', err)
        reject(err)
      })
    })
  }

  return {
    mobile: user_store.userInfo?.mobile,
    getPhoneNumber,
    getSendCode,
    mobileLogin: mobileLoginWithSms,
  }
}
